package com.zm.zmgz.service;

import com.zm.zmgz.dao.RevenueBeanMapper;
import com.zm.zmgz.pojo.CurrentUser;
import com.zm.zmgz.pojo.ProjectProfitBatchOptionBean;
import com.zm.zmgz.pojo.RevenueBean;
import com.zm.zmgz.pojo.RevenueBeanExample;
import com.zm.zmgz.utils.CollectionUtilszm;
import com.zm.zmgz.utils.DateUtils;
import com.zm.zmgz.utils.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/05/13/14:04
 * @Description:收支明细模块
 */
@Service
public class RevenueService {

    @Autowired
    RevenueBeanMapper revenueBeanMapper;

    @Autowired
    ProjectProfitService projectProfitService;

    /***
     * @Description:刷新某批次的统计记录
     * 先删除
     * 在添加
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 11:14:25
     */
    @Transactional
    public boolean refreshStatistics(Date date) {
        // 先删除该批次的项目统计记录
        int i = deleteProRevenues(date);
        // 再添加
        int j = addProRevenues(date);
        return true;
    }

    /***
     * @Description:
     * 添加某批次是项目盈利记录
     * 获取该月份所有项目盈利记录(按照项目名排序)
     * 遍历记录
     * 创建map集合,以项目名为key,项目盈利记录的利润为vaule,进行统计
     * 以项目统计map为数据新增收支记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-14 12:15:34
     */
    private int addProRevenues(Date date) {
        Date date2 = new Date(date.getTime()+86401000);
        Map<String, Double> map = projectProfitService.getProProfitStatistics(date);
        List<RevenueBean> list = new ArrayList<>();
        if (Objects.isNull(map) || map.size() == 0){ // 如果没有项目收支记录,就添加一条空记录
            RevenueBean revenueBean = new RevenueBean();
            revenueBean.setCreationdate(date2);
            revenueBean.setSettlementdate(date2);
            revenueBean.setSource("空记录");
            revenueBean.setRevenue("收入");
            revenueBean.setCreateuser(CurrentUser.getName());
            revenueBean.setKind("空记录");
            revenueBean.setAmount(0+"");
            list.add(revenueBean);
            return addRevenues(list);
        }
        for (String s : map.keySet()) {
            RevenueBean revenueBean = new RevenueBean();
            revenueBean.setCreationdate(date2);
            revenueBean.setSettlementdate(date2);
            revenueBean.setSource("项目盈利");
            revenueBean.setRevenue("收入");
            revenueBean.setCreateuser(CurrentUser.getName());
            revenueBean.setKind(s);
            revenueBean.setAmount(map.get(s) + "");
            list.add(revenueBean);
        }
        if (!Objects.isNull(list) && list.size() > 0)
            return addRevenues(list);
        else
            return 0;
    }

    /***
     * @Description: 添加收支记录集合
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-14 12:31:16
     */
    public int addRevenues(List<RevenueBean> list) {
        int i = 0;
        if (!Objects.isNull(list) && list.size() > 0) {
            for (RevenueBean revenueBean : list) {
                i += revenueBeanMapper.insert(revenueBean);
            }
        }
        return i;
    }

    /***
     * @Description: 删除该月份内项目统计收支记录
     * 条件获取记录(日期,source = '项目盈利')
     * 删除这些记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-14 11:53:02
     */
    @Transactional
    int deleteProRevenues(Date date) {
        Date monthStart = DateUtils.getMonthStart(date);
        Date monthEnd = DateUtils.getMonthEnd(date);
        RevenueBeanExample revenueBeanExample = new RevenueBeanExample();
        RevenueBeanExample.Criteria criteria = revenueBeanExample.createCriteria();
        criteria.andSettlementdateBetween(monthStart, monthEnd).andSourceEqualTo("项目盈利");
        List<RevenueBean> list = revenueBeanMapper.selectByExample(revenueBeanExample);
        if (Objects.isNull(list) || list.size() == 0)
            return 0;
        else {
            int i = 0;
            for (RevenueBean revenueBean : list) {
                i += revenueBeanMapper.deleteByPrimaryKey(revenueBean.getId());
            }
            return i;
        }
    }

    /***
     * @Description: 删除收支集合
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-14 12:08:47
     */
    @Transactional
    public int deleteRevenues(List<RevenueBean> list) {
        int i = 0;
        for (RevenueBean revenueBean : list)
            i += revenueBeanMapper.deleteByPrimaryKey(revenueBean.getId());
        return i;
    }


    /***
     * @Description: 提供日期, 获取该月份的收支明细数据
     *
     * 按照收支类型排序(先收入,在支出),种类(降序),具体(降序),数额(降序)
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 14:14:47
     */
    public List<RevenueBean> getRevenuesByDate(Date date, Integer page, Integer limit) {
        Date monthStart = DateUtils.getMonthStart(date);
        Date monthEnd = DateUtils.getMonthEnd(date);
        RevenueBeanExample revenueBeanExample = new RevenueBeanExample();
        RevenueBeanExample.Criteria criteria = revenueBeanExample.createCriteria();
        criteria.andCreationdateBetween(monthStart, monthEnd);
        revenueBeanExample.setOrderByClause("revenue DESC,source DESC,kind DESC,amount DESC");
        List<RevenueBean> list = revenueBeanMapper.selectByExample(revenueBeanExample);

        // 假分页
        if (!Objects.isNull(list) && list.size() > 0) {
            Integer total = list.size();
            if (page != 0 && limit != 0) {
                list = (List<RevenueBean>) CollectionUtilszm.getListPagination(list, page, limit);
            }
            list.get(0).setTotal(total);
            return list;
        } else
            return null;

    }

    /***
     * @Description: 添加一个收支明细记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 14:37:03
     */
    public int addRevenue(RevenueBean revenueBean) {
        return revenueBeanMapper.insert(revenueBean);
    }

    /***
     * @Description: 删除一个收支明细记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 14:37:03
     */
    public int deleteRevenue(@RequestBody RevenueBean revenueBean) {
        return revenueBeanMapper.deleteByPrimaryKey(revenueBean.getId());
    }

    /***
     * @Description: 更新一个收支明细记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 14:37:03
     */
    public int updateRevenue(RevenueBean revenueBean) {
        return revenueBeanMapper.updateByPrimaryKey(revenueBean);
    }


    /***
     * @Description: 获取批次选择数据
     * - 获取全部记录(排序:填写日期升序,数额降序;"settlementDate ASC,amount DESC")
     * - 遍历全部记录，创建数据对象集合
     *   - 获取时间，提取年，年级中是否存在该年
     *     - 有则提取月，判断月级中是否存在该月
     *       - 有则舍弃（看你是否要日级）
     *       - 无则创建该月级
     *     - 无则创建该年级
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-21 21:36:15
     */
    public List<ProjectProfitBatchOptionBean> getBatchOptions() {
        // 获取全部记录(排序:批次升序,项目名升序,利润降序;creationDate ASC, itemName asc,profit DESC)
        String order = "settlementDate ASC,amount DESC";
        List<RevenueBean> list = getAllAndOrder(order);
        if (Objects.isNull(list) || list.size() == 0)
            return null;
        // 遍历全部记录，创建数据对象集合,进行解析
        List<ProjectProfitBatchOptionBean> list1 = new ArrayList<>();
        for (RevenueBean revenueBean : list) {
            Date date = revenueBean.getSettlementdate();
            String year = DateUtils.getDateString(date, "YYYY年");
            String month = DateUtils.getDateString(date, "MM月");
            // 搜索是否存在该年;如果不存在就添加该年该月
            int i = 0;
            for (ProjectProfitBatchOptionBean bean : list1) {
                // 该年存在
                if (bean.getValue().equals(year)) {
                    // 搜索是否存在该月
                    List<ProjectProfitBatchOptionBean> list2 = bean.getChildren();
                    int j = 0;
                    // 遍历该年是否存在该月
                    for (ProjectProfitBatchOptionBean optionBean : list2) {
                        if (optionBean.getLabel().equals(month)) {
                            j++;
                            break;
                        }
                    }
                    // 该年存在,但该月不存在,添加月
                    if (j == 0) {
                        ProjectProfitBatchOptionBean optionBean1 = new ProjectProfitBatchOptionBean();
                        optionBean1.setValue(year + month);
                        optionBean1.setLabel(month);
                        bean.getChildren().add(optionBean1);
                    }
                    i++;
                    break;
                }
            }
            // 该年不存在
            if (i == 0) {
                ProjectProfitBatchOptionBean optionBean = new ProjectProfitBatchOptionBean();
                optionBean.setLabel(year);
                optionBean.setValue(year);
                optionBean.setChildren(new ArrayList<>());
                ProjectProfitBatchOptionBean optionBean1 = new ProjectProfitBatchOptionBean();
                optionBean1.setValue(year + month);
                optionBean1.setLabel(month);
                optionBean.getChildren().add(optionBean1);
                list1.add(optionBean);
            }

        }
        return list1;
    }

    /***
     * @Description: 获取所有记录并排序
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-24 21:25:09
     */
    private List<RevenueBean> getAllAndOrder(String order) {
        RevenueBeanExample revenueBeanExample = new RevenueBeanExample();
        revenueBeanExample.setOrderByClause(order);
        return revenueBeanMapper.selectByExample(revenueBeanExample);
    }


    /***
    * @Description: 通过写入时间月份查询记录集合中的种类字段集合
    * @Param:
    * @return:
    * @Author: cjw
    * @Date: 2020-06-02 19:27:01
    */
    public List<String> getSourceByDate(Date date) {
        if (Objects.isNull(date))
            return null;
        List<RevenueBean> list = getRevenuesByDate(date, 0, 0);
        if(Objects.isNull(list) || list.size() == 0)
            return null;
        List<String> list1 = new ArrayList<>();
        for (RevenueBean bean : list) {
            String source = bean.getSource();
            // 去重复
            Boolean b = ListUtils.isExistStringFromList(source, list1);
            if(!b)
                list1.add(source);

        }
        return list1;
    }

    /***
    * @Description: 通过批次和source获取记录集合
    * @Param:
    * @return:
    * @Author: cjw
    * @Date: 2020-06-02 20:51:32
    */
    public List<RevenueBean> getRevenuesByDateAndSource(Date date, String source) {
        if(Objects.isNull(date) || Objects.isNull(source))
            return null;
        Date monthStart = DateUtils.getMonthStart(date);
        Date monthEnd = DateUtils.getMonthEnd(date);
        RevenueBeanExample revenueBeanExample = new RevenueBeanExample();
        RevenueBeanExample.Criteria criteria = revenueBeanExample.createCriteria();
        criteria.andCreationdateBetween(monthStart, monthEnd).andSourceEqualTo(source);
        revenueBeanExample.setOrderByClause("revenue DESC,source DESC,kind DESC,amount DESC");
        List<RevenueBean> list = revenueBeanMapper.selectByExample(revenueBeanExample);
        if(Objects.isNull(list) || list.size() == 0)
            return null;
        else
            return list;

    }
}
